<template>
  <div>
    <el-row>
      <el-col :span="4">
        <el-input placeholder="请输入分类名" @change="addTableData" v-model="input" clearable>
          <el-button slot="append">新增</el-button>
        </el-input>
      </el-col>
    </el-row>
    <!--  -->
    <el-table :data="tableData" stripe style="width: 100%;margin-top:20px" border>
      <el-table-column type="index" label="#" width="50"></el-table-column>
      <el-table-column prop="name" label="类别名" width="1450">
        <template slot-scope="scope">
          <div v-if="index == scope.$index">
            <el-input v-model="input1" style="width:100px;margin-right:15px"></el-input>
            <el-button type="danger" size="small" @click="this.input1 = ''">取消</el-button>
            <el-button type="success" size="small" @click="editTableData(scope.row.id)">确认</el-button>
          </div>
          <div v-else>{{scope.row.name}}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="163">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row,'删除')" type="danger" size="small">删除</el-button>
          <el-button
            @click="handleClick(scope.row,'编辑',scope.$index)"
            type="success"
            size="small"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
export default {
  layout: "mine",
  data() {
    return {
      input: "",
      input1: "",
      index: -1
    };
  },
  async fetch({ $axios, store }) {
    store.dispatch("classify/getData");
  },
  methods: {
    ...mapActions("classify", ["getData", "addData", "editData", "delData"]),
    async handleClick(row, val, index) {
      if (val == "编辑") {
        this.index = index;
        this.input1 = row.name;
      } else if (val == "删除") {
        await this.delData(row.id);
        this.getData();
      }
    },
    // 新增
    async addTableData() {
      if (this.input) {
        await this.addData({ name: this.input });
        this.getData();
        this.input = "";
      }
    },
    // 修改
    async editTableData(id) {
      await this.editData({ name: this.input1, id });
      this.index = -1;
      this.getData();
    }
  },
  computed: {
    ...mapState("classify", ["data"]),
    tableData() {
      console.log(this.data);
      return this.data;
    }
  }
};
</script>

<style scoped>
</style>